from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.models.role import Role as RoleModel, RoleInDB
from app.schemas.role import Role as RoleSchema, RoleCreate, RoleUpdate
from app.schemas.response import APIResponse, PaginatedResponse
from app.config.database import get_db
from app.utils.responses import success_response, error_response, paginated_response
from app.utils.logger import logger
from datetime import datetime

router: APIRouter = APIRouter(prefix="/roles", tags=["角色管理"])

@router.post("/create", response_model=APIResponse[RoleSchema])
def create_role(role: RoleCreate, db: Session = Depends(get_db)):
    logger.info(f"Creating role with role_code: {role.role_code}")
    
    # 检查角色编码是否已存在
    db_role = db.query(RoleModel).filter(RoleModel.role_code == role.role_code).first()
    if db_role:
        logger.warning(f"Role code already registered: {role.role_code}")
        return error_response(message="Role code already registered", code=400)
    
    # 创建新角色
    db_role = RoleModel(
        role_code=role.role_code,
        role_name=role.role_name,
        role_desc=role.role_desc,
        status=role.status,
        create_time=datetime.utcnow(),
        update_time=datetime.utcnow()
    )
    
    db.add(db_role)
    db.commit()
    db.refresh(db_role)
    
    # 转换为Pydantic模型
    role_response = RoleInDB.model_validate(db_role)
    
    logger.info(f"Role created successfully with ID: {db_role.id}")
    return success_response(data=role_response, message="Role created successfully")

@router.get("/list", response_model=APIResponse[PaginatedResponse[RoleSchema]])
def read_roles(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    logger.info(f"Fetching roles with skip: {skip}, limit: {limit}")
    
    roles = db.query(RoleModel).offset(skip).limit(limit).all()
    # 转换为Pydantic模型
    roles_response = [RoleInDB.model_validate(role) for role in roles]
    total = db.query(RoleModel).count()
    
    logger.info(f"Found {len(roles)} roles")
    return paginated_response(
        items=roles_response,
        total=total,
        page=skip // limit + 1,
        size=limit
    )

@router.get("/{role_id}", response_model=APIResponse[RoleSchema])
def read_role(role_id: int, db: Session = Depends(get_db)):
    logger.info(f"Fetching role with ID: {role_id}")
    
    db_role = db.query(RoleModel).filter(RoleModel.id == role_id).first()
    if db_role is None:
        logger.warning(f"Role not found with ID: {role_id}")
        return error_response(message="Role not found", code=404)
    
    # 转换为Pydantic模型
    role_response = RoleInDB.model_validate(db_role)
    
    logger.info(f"Role found with ID: {role_id}")
    return success_response(data=role_response)

@router.put("/{role_id}", response_model=APIResponse[RoleSchema])
def update_role(role_id: int, role: RoleUpdate, db: Session = Depends(get_db)):
    logger.info(f"Updating role with ID: {role_id}")
    
    db_role = db.query(RoleModel).filter(RoleModel.id == role_id).first()
    if db_role is None:
        logger.warning(f"Role not found with ID: {role_id}")
        return error_response(message="Role not found", code=404)
    
    # 更新角色信息
    update_data = role.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_role, key, value)
    
    db_role.update_time = datetime.utcnow()
    db.commit()
    db.refresh(db_role)
    
    # 转换为Pydantic模型
    role_response = RoleInDB.model_validate(db_role)
    
    logger.info(f"Role updated successfully with ID: {role_id}")
    return success_response(data=role_response, message="Role updated successfully")

@router.delete("/{role_id}", response_model=APIResponse[None])
def delete_role(role_id: int, db: Session = Depends(get_db)):
    logger.info(f"Deleting role with ID: {role_id}")
    
    db_role = db.query(RoleModel).filter(RoleModel.id == role_id).first()
    if db_role is None:
        logger.warning(f"Role not found with ID: {role_id}")
        return error_response(message="Role not found", code=404)
    
    db.delete(db_role)
    db.commit()
    
    logger.info(f"Role deleted successfully with ID: {role_id}")
    return success_response(message="Role deleted successfully")
